package com.junjie.interceptor;

import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.junjie.utils.CommonParams;
import com.junjie.utils.CommonResult;
import com.junjie.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//JWT的拦截器，如果没有登陆的话其它的接口都是不能够访问的
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CommonResult msg = new CommonResult();
        String token = request.getHeader("Authorization");//拿到token字段
        //处理业务逻辑
        try {
            JWTUtils.verify(token);
            return true;
        } catch (SignatureVerificationException e){
            System.out.println("签名不一致异常");
            msg.setMessage("签名不一致异常");
        } catch (TokenExpiredException e) {
            System.out.println("令牌过期异常");
            msg.setMessage("令牌过期异常");
        } catch (ArithmeticException e) {
            System.out.println("算法不匹配异常");
            msg.setMessage("算法不匹配异常");
        } catch (InvalidClaimException e) {
            System.out.println("失败payload异常");
            msg.setMessage("失败payload异常");
        } catch (Exception e) {
            System.out.println("总异常");
            msg.setMessage("总异常");
        }
        msg.setCode(CommonParams.VERIFY_FAILURE);
        //将 CommonResult 转为 Json jackson
        String json = new ObjectMapper().writeValueAsString(msg);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
